package com.jyskkebank.android.toggl;

import com.jyskkebank.android.toggl.Base64Converter;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class TogglUtil {
	private static final String SESSIONS_URL = "https://www.toggl.com/api/v6/sessions.json";
	private static final String PROJECTS_URL = "https://www.toggl.com/api/v6/projects.json";
	private static final String TASKS_URL = "https://www.toggl.com/api/v6/tasks.json";
	private static final String TIME_ENTRIES_URL = "https://www.toggl.com/api/v6/time_entries.json";
	
	private String method;
	
	public TogglUtil(){
		// default construstor
	}
	
	public String fetchLoginData(String email, String password) {
		String authData = email + ":" + password;
		StringBuffer returnData = new StringBuffer();
		try{
		URL url = new URL(SESSIONS_URL);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		String encoded = Base64Converter.encode (authData.getBytes());
		conn.setRequestProperty ("Authorization", "Basic " + encoded);
		OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
		System.out.println("connected");
		
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String inputLine = null;
		while ((inputLine = in.readLine()) != null){ 
			System.out.println(inputLine);
			returnData.append(inputLine);
		}
		in.close();
		out.close();
		System.out.println("connected");
		} catch (IOException e) { 
			System.out.println("exception: " + e);
		}
		return returnData.toString();
	}

	public String fetchProjects(String apiToken) throws IOException {
		System.out.println("fetchProjects >>>>>>>");
		String response = null;
		try{
			URL url = new URL(PROJECTS_URL);
			response = fetchContents(url, apiToken);
			System.out.println("projects fetched>>>>>>>");
		} catch (IOException e){
			System.out.println("Exception in fetchProjects >>>>>>>>");
			System.out.println(e.getMessage());
		}
		return response;
	}

	public String fetchTasks(String apiToken) throws IOException {
		System.out.println("fetchTasks >>>>>>>");
		String response = null;
		try{
			URL url = new URL(TASKS_URL);
			response = fetchContents(url, apiToken);
			System.out.println("tasks fetched>>>>>>>");
		} catch (IOException e){
			System.out.println("Exception in fetchTasks >>>>>>>>");
			System.out.println(e.getMessage());
		}
		return response;
	}
	
	public String fetchTimeEntries(String apiToken) throws IOException {
		System.out.println("fetchTimeEntries >>>>>>>");
		String response = null;
		try{
			URL url = new URL(TIME_ENTRIES_URL);
			response = fetchContents(url, apiToken);
			System.out.println("TimeEntries fetched>>>>>>>");
		} catch (IOException e){
			System.out.println("Exception in fetchTimeEntries >>>>>>>>");
			System.out.println(e.getMessage());
		}
		return response;
	}

	public String updateTimeEntry(String apiToken, Long taskId, String timeEntry){
		System.out.println("updateTimeEntry >>>>>>>");
		String response = null;
		try{
			URL url = null;
			if(taskId != 0){
				method = "PUT";
				url = new URL("https://www.toggl.com/api/v6/time_entries/" + taskId + ".json");
			}else{
				method = "GET";
				url = new URL("https://www.toggl.com/api/v6/time_entries.json");
			}
			System.out.println("URL : " + url);
			response = saveContents(url, apiToken, timeEntry);
			System.out.println("TimeEntry updated>>>>>>> " + response);
		} catch (IOException e){
			System.out.println("Exception in updateTimeEntry >>>>>>>>");
			System.out.println(e.getMessage());
		}
		return response;
	}
	
	public String deleteTimeEntry(String apiToken, String taskId) {
		System.out.println("deleteTimeEntry >>>>>>>"+apiToken+" "+taskId);
		String response = null;
		method = "DELETE";
		try{
			URL url = new URL("https://www.toggl.com/api/v6/time_entries/" + taskId + ".json"); 
			response = saveContents(url, apiToken, null);
			System.out.println("TimeEntry deleted >>>>>>> " + response);
		} catch (IOException e){
			System.out.println("Exception in updateTimeEntry >>>>>>>>");
			System.out.println(e.getMessage());
		}
		return response;
	}

	// private methods go here
	private String saveContents(URL url, String apiToken, String timeEntry) throws IOException {
		String authData = apiToken + ":api_token";
		StringBuffer returnData = new StringBuffer();
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod(method);
		String auth = Base64Converter.encode(authData.getBytes());
		conn.setRequestProperty("Content-type","application/json");
		conn.setRequestProperty ("Authorization", "Basic " + auth);
		DataOutputStream out = null;
		BufferedReader in = null;
		try{
			if(null != timeEntry){
				out = new DataOutputStream(conn.getOutputStream());
				out.writeBytes(timeEntry);
				out.flush();
				out.close();
			}
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		} catch (IOException e){
			System.out.println("Exception : " + e.getMessage());
			System.out.println("--------" + conn.getResponseMessage());
			for (String key : conn.getHeaderFields().keySet()) {
				List<String> stringList = conn.getHeaderFields().get(key);
				System.out.println(key + "--------" + stringList);
			}
			in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
		}
		String inputLine = null;
		while ((inputLine = in.readLine()) != null){ 
			System.out.println(inputLine);
			returnData.append(inputLine);
		}
		in.close();
		return returnData.toString();
	}

	private String fetchContents(URL url, String apiToken) throws IOException {
		String authData = apiToken+":api_token" ;
		StringBuffer returnData = new StringBuffer();
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		String data = Base64Converter.encode(authData.getBytes());
		conn.setRequestProperty("Content-type","application/json; charset=" + "UTF-8");
		conn.setRequestProperty ("Authorization", "Basic " + data);
		BufferedReader in = null;
		try{
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		} catch (IOException e){
			System.out.println("Exception : " + e.getMessage());
			for (String key : conn.getHeaderFields().keySet()) {
				List<String> stringList = conn.getHeaderFields().get(key);
				System.out.println(key + "--------" + stringList);
			}
			in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
		}
		String inputLine = null;
		while ((inputLine = in.readLine()) != null){ 
			System.out.println(inputLine);
			returnData.append(inputLine);
		}
		in.close();
		return returnData.toString();
	}
	
}
